
#include <Archaism/File.h>
#include <Archaism/String.h>

_BeginNamespace(Radix)
/*
=================================================================
== universal macros
=================================================================
*/
#if(_RADIX_STRINGTYPE == _RADIX_STRINGTYPE_MBS)
#define _OpenFile(name, mode) fopen(name, mode)
#elif(_RADIX_STRINGTYPE == _RADIX_STRINGTYPE_WCS)
#define _OpenFile(name, mode) _wfopen(name, mode)
#endif
/*
=================================================================
== File
=================================================================
*/
File::File(const String& fileName, const String& openMode)
	:mName(fileName),
	mMode(openMode),
	mHandle(nullptr)
{}

File::~File()
{
	this->close();
}

bool File::open()
{
	if(mHandle != nullptr)
		return true;
	mHandle = _OpenFile(mName.c_str(), mMode.c_str());
	return mHandle != nullptr;
}

void File::close()
{
	if(mHandle != nullptr)
	{
		fclose(mHandle);
		mHandle = nullptr;
	}
}

bool File::isOpen()
{
	return mHandle != nullptr;
}

bool File::readable()
{
	return StringUtil::startsWith(mMode, _T("r"));
}

bool File::writable()
{
	return StringUtil::startsWith(mMode, _T("w")) ||
		StringUtil::startsWith(mMode, _T("a"));
}

uint File::read(void* bytes, uint length)
{
	return fread(bytes, length, 1, mHandle);
}

uint File::write(void* bytes, uint length)
{
	return fwrite(bytes, length, 1, mHandle);
}

bool File::seek(int offset, int origin)
{
	return fseek(mHandle, offset, origin) == 0;
}

bool File::eos()
{
	return feof(mHandle) != 0;
}

void File::flush()
{
	fflush(mHandle);
}

_EndNamespace(Radix)
